<template>
    <div class="verification-code-input">
      <div 
        class="code-wrapper"
        :class="{ 'has-error': hasError }"
      >
        <input
          v-for="(digit, index) in 6"
          :key="index"
          ref="inputs"
          v-model="digits[index]"
          type="text"
          maxlength="1"
          :class="{ active: currentIndex === index }"
          @input="handleInput($event, index)"
          @keydown="handleKeydown($event, index)"
          @focus="currentIndex = index"
        >
      </div>
    </div>
  </template>
  
  <script lang="ts">
  import { defineComponent } from 'vue'
  
  export default defineComponent({
    name: 'VerificationCodeInput'
  })
  </script>
  
  <script setup lang="ts">
  import { ref, watch } from 'vue'
  
  const props = defineProps({
    code: {
      type: String,
      required: true
    },
    hasError: {
      type: Boolean,
      default: false
    }
  })
  
  const emit = defineEmits(['update:code', 'complete'])
  
  const digits = ref(Array(6).fill(''))
  const inputs = ref<HTMLInputElement[]>([])
  const currentIndex = ref(0)
  
  watch(() => props.code, (newCode) => {
    if (!newCode) {
      digits.value = Array(6).fill('')
      currentIndex.value = 0
    }
  }, { immediate: true })
  
  watch(digits, (newDigits) => {
    const code = newDigits.join('')
    emit('update:code', code)
    
    if (code.length === 6) {
      emit('complete')
    }
  }, { deep: true })
  
  const handleInput = (event: Event, index: number) => {
    const input = event.target as HTMLInputElement
    const value = input.value
    
    if (!/^\d*$/.test(value)) {
      digits.value[index] = ''
      return
    }
    
    if (value && index < 5) {
      currentIndex.value = index + 1
      inputs.value[index + 1]?.focus()
    }
  }
  
  const handleKeydown = (event: KeyboardEvent, index: number) => {
    if (event.key === 'Backspace' && !digits.value[index] && index > 0) {
      currentIndex.value = index - 1
      inputs.value[index - 1]?.focus()
      digits.value[index - 1] = ''
    }
  }
  </script>
  
  <style lang="scss" scoped>
  .verification-code-input {
    .code-wrapper {
      display: flex;
      gap: 8px;
      justify-content: center;
      
      &.has-error input {
        border-color: #ff4d4f;
        
        &:focus {
          border-color: #ff4d4f;
          box-shadow: 0 0 0 2px rgba(255, 77, 79, 0.2);
        }
      }
      
      input {
        width: 40px;
        height: 40px;
        border: 1px solid #d9d9d9;
        border-radius: 4px;
        text-align: center;
        font-size: 18px;
        transition: all 0.2s ease;
        background: #fff;
        
        &:focus {
          outline: none;
          border-color: #40a9ff;
          box-shadow: 0 0 0 2px rgba(24, 144, 255, 0.2);
        }
        
        &.active {
          border-color: #40a9ff;
        }
      }
    }
  }
  </style> 